
// pages/announcement/announcement.js
const db = wx.cloud.database()
const app = getApp();
Page({
  data: {
    dormitoryId:0,
    userImg: '',//头像
    userIDs: '',//用户名
    name:'',//公告名
    content:'',
    time:''  
  },
  getAvatarAndName() {
    const db = wx.cloud.database();
    const dormitoryCollection = db.collection('dormitory');
    const userInfoCollection = db.collection('userInfo');
    const openid = app.globalData.openid; // 从小程序实例的全局数据中获取openid
  
    dormitoryCollection.where({
      dormitoryId: this.data.dormitoryId
    }).field({
      member: true
    }).get().then(dormRes => {
      const dormData = dormRes.data[0];
      const members = dormData.member;
  
      const currentUser = members.find(member => member.openid === openid);
      if (currentUser) {
        this.setData({
          userIDs: currentUser.name
        });
  
        userInfoCollection.where({
          openid: openid
        }).get().then(userInfoRes => {
          const userInfoData = userInfoRes.data;
          if (userInfoData.length > 0 && userInfoData[0].avatar) {
            this.setData({
              userImg: userInfoData[0].avatar
            });
          }
        }).catch(err => {
          console.error('获取用户信息失败', err);
        });
      }
    }).catch(err => {
      console.error('获取宿舍信息失败', err);
    });
  },  
  submit: function () {
    wx.showLoading({
      title: '提交中',
    })

    //获取当前时间
    const now = new Date();
    const time = now.toLocaleString();

    // 获取输入框的值
    const name = this.data.name
    const content = this.data.content

    //先自定义用户的头像和ID（待登录）*****
    this.getAvatarAndName();
  
    // 检查必填项
    if (!name || !content) {
      wx.showToast({
        title: '标题和内容不能为空哦',
        icon: 'none',
        duration: 2000
      })
      wx.hideLoading()
      return
    }

    const announcement_db = db.collection('announcement_db');
    const announcementId = this.data.announcementId;
  
    if (announcementId) {
      announcement_db.doc(announcementId).update({
        data: {
          dormitoryId:this.data.dormitoryId,
          userImg:this.data.userImg,
          userIDs:this.data.userIDs,
          name: name,
          content:content,
          time:time
        }
      }).then(res => {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: '更新成功',
        })  
        // 更新成功后返回上一页
        wx.navigateBack()
      }).catch(error => {
        console.log(error)
        wx.hideLoading()
        wx.showToast({
          title: '更新失败，请重试',
        })
      })
    } else {
      announcement_db.add({
        data: {
          dormitoryId:this.data.dormitoryId,
          userImg:this.data.userImg,
          userIDs:this.data.userIDs,
          name: name,
          content:content,
          time:time
        }
      }).then(res => {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: '发布成功',
        })  
        // 发布成功后返回上一页
        wx.navigateBack()
      }).catch(error => {
        console.log(error)
        wx.hideLoading()
        wx.showToast({
          title: '发布失败，请重试',
        })
      })
    }
  },
  
 
  // 更新标题
updateName: function (event) {
  const value = event.detail.value;
  if (value.length > 15) {
    wx.showToast({
      icon: 'none',
      title: '标题不得超过15个字符',
    })
    return;
  }
  this.setData({
    name: value
  })
},

// 更新内容
updateContent: function (event) {
  this.setData({
    content: event.detail.value
  })
},

onLoad: function(options) {
  //先自定义用户的头像和ID（待登录）*****
    // 获取小程序实例
   const dormitoryId = app.globalData.dormitoryId; 
    console.log(dormitoryId);
    this.setData({
      dormitoryId:dormitoryId
    });
  this.getAvatarAndName();

  //获取当前时间
  const now = new Date();
  const time = now.toLocaleString();

  const selectedAnnouncement = options && options.announcement ? JSON.parse(options.announcement) : {};
  const announcementId = options && options.id ? options.id : '';
  
  // 将传递过来的信息设置到页面的数据中
  this.setData({
    announcementId: announcementId,
    name: selectedAnnouncement.name || '', // 使用空字符串作为默认值
    content: selectedAnnouncement.content || '', // 使用空字符串作为默认值
    userIDs: this.data.userIDs,
    userImg:this.data.userImg,
    time: time,
    namePlaceholder: '',
    contentPlaceholder: '请输入内容',
  });
},

})